package funcktion;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;

public class User extends JFrame {
    private JTable table;

    public User() {
        setTitle("User Table ");
//        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 400);
        setLocationRelativeTo(null);


        table = new JTable();
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        // 获取数据库连接
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "lang520520");

            // 执行查询语句
            String query = "SELECT * FROM user";
            Statement statement = conn.createStatement();
            ResultSet resultSet = statement.executeQuery(query);

            // 创建表格模型
            DefaultTableModel tableModel = new DefaultTableModel();
            table.setModel(tableModel);

            // 获取列信息
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                tableModel.addColumn(columnName);
            }

            // 添加行数据
            while (resultSet.next()) {
                Object[] rowData = new Object[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    rowData[i - 1] = resultSet.getObject(i);
                }
                tableModel.addRow(rowData);
            }

            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
